﻿using Dapper;
using ERPEF.Model;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.HttpResults;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.IdentityModel.Tokens;
using S4Project;
using S4Project.Model;
using System.Data;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;

namespace UI.Controllers
{
    [Route("api/[controller]/[action]")]
    [ApiController]
    [Consumes("application/json")]
    public class UserController : ControllerBase
    {
        private readonly MyDbContext MyDbContext;
        private Dictionary<string, string> _verifyCodes = new Dictionary<string, string>();
        private object _lock = new object();
        public UserController(MyDbContext myDb) 
        {
            this.MyDbContext = myDb;
        }

        /// <summary>
        /// 登录
        /// </summary>
        /// <param name="UserName"></param>
        /// <param name="UserPWD"></param>
        /// <returns></returns>
        /// 
        [HttpPost]
        public async Task<ActionResult<User>> Login([FromBody] User model)
        {
            var user = await MyDbContext.User.FirstOrDefaultAsync(e => e.UserName == model.UserName);
            if (user == null)
            {
                return NotFound(new { message = "用户不存在" });
            }
            // 然后验证密码是否正确
            if (!PasswordHelper.VerifyHash(model.UserPWD, user.UserPWD))
            {
                return Unauthorized(new { message = "密码错误" });
            }

            // 如果用户名和密码都匹配，生成JWT令牌
            var token = GenerateJwtToken(user);
            return Ok(new { token = token,UserId = user.UserID });
        }
        /// <summary>
        /// 登录进行加密
        /// </summary>
        /// <param name="user"></param>
        /// <returns></returns>
        private string GenerateJwtToken(User user)
        {
            var securityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("kehanshizhizhu0104zyxkhshizhizhu")); // 请替换为您的密钥
            var credentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256);

            var claims = new[]
            {
        new Claim(JwtRegisteredClaimNames.Sub, user.UserName),
        new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
        // 可以添加其他用户信息或者自定义的声明
    };
            var tokenDescriptor = new SecurityTokenDescriptor
            {
                Subject = new ClaimsIdentity(claims),
                Expires = DateTime.UtcNow.AddMinutes(5), 
                SigningCredentials = credentials
            };

            // 创建 JWT 处理实例
            var tokenHandler = new JwtSecurityTokenHandler();

            // 使用 tokenHandler 创建 JWT 令牌
            var securityToken = tokenHandler.CreateToken(tokenDescriptor);
            // 使用 tokenHandler 写入 JWT 令牌
            var tokenString = tokenHandler.WriteToken(securityToken);

            return tokenString;
        }
       /// <summary>
       /// 注册
       /// </summary>
       /// <param name="user"></param>
       /// <returns></returns>
        [HttpPost]
        public async Task<ActionResult> Register([FromBody] User user)
        {
            
            //验证用户是否存在
            if (await MyDbContext.User.AnyAsync(e => e.UserName == user.UserName))
            {
                return Content("用户名已存在，请使用其他用户名注册。");
            }

            // 对密码进行哈希处理
            user.UserPWD = PasswordHelper.GenerateHash(user.UserPWD);

            MyDbContext.User.Add(user);
            await MyDbContext.SaveChangesAsync();
            return Ok();
        }

        //判断用户名是否存在
        [HttpGet]
        public async Task<ActionResult> CheckUserNameExists(string userName)
        {
            var exists = await MyDbContext.User.AnyAsync(e => e.UserName == userName);
            return Ok(new { exists });
        }

        //数据库密码加密
        public static class PasswordHelper
        {
            public static string GenerateHash(string password)
            {
                using (Rfc2898DeriveBytes rbg = new Rfc2898DeriveBytes(password, Encoding.UTF8.GetBytes("Zyxshizhizhu0716"), 1000))
                {
                    return Convert.ToBase64String(rbg.GetBytes(20));
                }
            }
            public static bool VerifyHash(string password, string hash)
            {
                using (Rfc2898DeriveBytes rbg = new Rfc2898DeriveBytes(password, Encoding.UTF8.GetBytes("Zyxshizhizhu0716"), 1000))
                {
                    string newHash = Convert.ToBase64String(rbg.GetBytes(20));
                    return newHash == hash;
                }
            }
        }
        [HttpPost]
        public async Task<ActionResult> ChangePassword([FromBody] ChangePasswordDTO model)
        {
            // 验证输入的密码是否有效
            if (string.IsNullOrWhiteSpace(model.NewPassword) ||
                model.NewPassword == model.OldPassword)
            {
                return BadRequest("新密码和确认密码不匹配或为空，且新密码不能与旧密码相同");
            }

            // 检查用户是否存在
            var user = await MyDbContext.User.FirstOrDefaultAsync(u => u.UserName == model.Username);
            if (user == null)
            {
                return BadRequest("用户不存在");
            }

            // 验证当前密码是否正确
            if (!PasswordHelper.VerifyHash(model.OldPassword, user.UserPWD))
            {
                return BadRequest("当前密码不正确");
            }

            // 更新密码
            user.UserPWD = PasswordHelper.GenerateHash(model.NewPassword);
            await MyDbContext.SaveChangesAsync();

            return Ok("密码修改成功");
        }

        // 生成验证码
        public string GenerateVerifyCode(int length = 6)
        {
            const string validChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890";
            var random = new Random();
            var code = new char[length];
            for (int i = 0; i < length; i++)
            {
                code[i] = validChars[random.Next(validChars.Length)];
            }
            return new string(code);
        }

        // 存储验证码
        public void SaveVerifyCode(string key, string code)
        {
            lock (_lock)
            {
                _verifyCodes[key] = code;
                // 设置验证码过期时间，例如10分钟
                System.Threading.Tasks.Task.Delay(1 * 60 * 1000).ContinueWith(task =>
                {
                    lock (_lock)
                    {
                        _verifyCodes.Remove(key);
                    }
                });
            }
        }
        // 验证验证码
        public bool VerifyCode(string key, string code)
        {
            lock (_lock)
            {
                if (_verifyCodes.TryGetValue(key, out var storedCode) && storedCode.Equals(code, StringComparison.OrdinalIgnoreCase))
                {
                    return true;
                }
            }
            return false;
        }

        
    }
}
